/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.util;

import java.text.DecimalFormat;

import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.constants.EnumConstants;

/**
 * 金额相关工具类
 *
 * @version v1.0.0 @author zouzhigang 2014-2-27 新建与整理
 */
@AnAlias("Amounts")
public class Amounts implements EnumConstants
{   
    /**
     * 金额分，转为字符串元，转化后是2位小数点
     * 
     * @param fen   金额分值，能转化成长整型的字符串
     * @return      金额元值字符串
     */
    public static String toYuan(String fen)
    {
        Asserts.asInteger(fen);
        return toYuan(Long.parseLong(fen));
    }
    
    /**
     * 金额分，转为字符串元，转化后最大2位小数点，没有的不保留小数点（0.##）
     * 
     * @param fen   金额分值
     * @return      金额元值字符串
     */
    public static String toYuan(long fen)
    {
        return new DecimalFormat("0.##").format((double)fen / 100);
    }
    
    /**
     * 金额分，转为字符串元，转化后强制为2位小数点，没有的为（0.00）
     * 
     * @param fen   金额分值
     * @return      金额元值字符串
     */
    public static String toYuanMustRadix(String fen)
    {
        Asserts.asInteger(fen);
        return toYuanMustRadix(Long.parseLong(fen));
    }
    
    /**
     * 金额分，转为字符串元，转化后强制为2位小数点，没有的为（0.00）
     * 
     * @param fen   金额分值
     * @return      金额元值字符串，如"2.00"
     */
    public static String toYuanMustRadix(long fen)
    {
        return new DecimalFormat("0.00").format((double)fen / 100);
    }
    
    /**
     * 金额元字符串转int金额分，支持整数、1位小数和2位小数点的金额字符串
     * 
     * @param yuan          金额元的字符串
     * @param defaultValue  缺省值
     * @return              金额分整型
     */
    public static int toFen(String yuan, int defaultValue)
    {
        if (yuan == null)
            return defaultValue;
        
        if (!Validates.isAmount2R(yuan))
            return defaultValue;
        
        boolean isNegative = false;
        if (yuan.startsWith("-"))
        {
            isNegative = true;
            yuan = yuan.substring(1);
        }
        
        int index = yuan.indexOf('.');
        if (index == -1)
        {
            int value = Integer.parseInt(yuan) * 100;//由元转为分
            return (isNegative)?-value:value;
        }
        
        int integer = Integer.parseInt(yuan.substring(0, index)) * 100;
        String radixString = yuan.substring(index + 1);
        if (radixString.length() == 0)
        {
            return (isNegative)?-integer:integer;
        }
        else if (radixString.length() == 1)
        {
            int radix = Integer.parseInt(radixString);
            int value = integer + radix * 10;
            return (isNegative)?-value:value;
        }
        else
        {
            int radix = Integer.parseInt(radixString);
            int value = integer + radix;
            return (isNegative)?-value:value;
        }
    }
    
    /**
     * 金额元字符串转long金额分，支持整数、1位小数和2位小数点的金额字符串
     * 
     * @param yuan          金额元的字符串
     * @param defaultValue  缺省值
     * @return              金额分的长整型
     */
    public static long toFen(String yuan, long defaultValue)
    {
        if (yuan == null)
            return defaultValue;
        
        if (!Validates.isAmount2R(yuan))
            return defaultValue;
        
        boolean isNegative = false;
        if (yuan.startsWith("-"))
        {
            isNegative = true;
            yuan = yuan.substring(1);
        }
        
        int index = yuan.indexOf('.');
        if (index == -1)
        {
            long value = Long.parseLong(yuan) * 100;//由元转为分
            return (isNegative)?-value:value;
        }
        
        long integer = Long.parseLong(yuan.substring(0, index)) * 100;
        String radixString = yuan.substring(index + 1);
        if (radixString.length() == 0)
        {
            return (isNegative)?-integer:integer;
        }
        else if (radixString.length() == 1)
        {
            long radix = Long.parseLong(radixString);
            long value = integer + radix * 10;
            return (isNegative)?-value:value;
        }
        else
        {
            long radix = Long.parseLong(radixString);
            long value = integer + radix;
            return (isNegative)?-value:value;
        }
    }
    
    /** 
     * 获取中文大写金额值 
     * 
     * @param value 单位为分的金额值
     */
    public static String toChinese(int value) 
    {
        double src = Integer.valueOf(value).doubleValue();
        src = src/100;
        
        StringBuilder sb = new StringBuilder();
        DecimalFormat df = new DecimalFormat("0.00");
        String srcText = df.format(src);
        String numText = srcText.substring(0, srcText.length() - 3);
        String decText = srcText.substring(srcText.length() - 2);

        int numlen = numText.length();
        for (int k = 0; k < numlen; k++) 
        {
            sb.append(_RMB_NUM_[Integer.parseInt(String.valueOf(srcText.charAt(k)))]);
            sb.append(_RMB_UNIT_[numlen - k - 1]);
        }
        if ("00".equals(decText))
        {
            sb.append("整");
        } 
        else
        {
            sb.append(_RMB_NUM_[Integer.parseInt(String.valueOf(decText.charAt(0)))]);
            sb.append(_RMB_DEC_[0]);
            sb.append(_RMB_NUM_[Integer.parseInt(String.valueOf(decText.charAt(1)))]);
            sb.append(_RMB_DEC_[1]);
        }
        String result = sb.toString();
        result = result.replace("零分", _EMPTY_);
        result = result.replace("零角", "零");
        result = result.replace("零仟", "零");
        result = result.replace("零佰", "零");
        result = result.replace("零拾", "零");
        result = result.replace("零圆", "圆");
        while (true)
        {
            String r = result.replace("零零", "零");
            if (r.equals(result))
            {
                break;
            } 
            else 
            {
                result = r;
            }
        }
        result = result.replace("零圆", "圆");
        result = result.replace("零万", "万");
        result = result.replace("零亿", "亿");
        result = result.replace("亿万", "亿");
        if(result.startsWith("圆"))
        {
            result="零"+result;
        }
        return result;
    }
    
    /**
     * 通过原价和促销价，求折扣
     * 
     * @param price     原价
     * @param priceNew  促销价
     * @return 返回减钱折扣值，如9.92折,10折
     */
    public static String toDiscount(String price, String priceNew)
    {
        long priceLong = toFen(price, 0);
        long priceNewLong = toFen(priceNew, 0);
        return toDiscount(priceLong, priceNewLong);
    }
    
    /**
     * 通过原价和促销价，求折扣
     * 
     * @param price     原价
     * @param priceNew  促销价
     * @return 返回减钱折扣值，如9.92折,10折
     */
    public static String toDiscount(long price, long priceNew)
    {
        long priceSave = price - priceNew;
        if (priceSave == 0)
            return "10";
        else
            return toYuan(priceNew * 1000 / price);
    }
}
